import React, { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  GitBranch,
  Edit,
  Trash2,
  Plus,
  ChevronLeft,
  ChevronRight,
  SkipBack,
  SkipForward,
} from "lucide-react";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

// 数值格式化函数 - 限制最多两位小数
const formatNumber = (value) => {
  if (value === null || value === undefined || value === "") return "-";
  
  const num = parseFloat(value);
  if (isNaN(num)) return value;
  
  // 如果是整数，不显示小数部分
  if (Number.isInteger(num)) {
    return num.toString();
  }
  
  // 限制最多两位小数，去掉末尾的0
  return parseFloat(num.toFixed(2)).toString();
};

// 数值格式化函数 - 强制显示两位小数（适用于需要固定格式的情况）
const formatNumberFixed = (value) => {
  if (value === null || value === undefined || value === "") return "-";
  
  const num = parseFloat(value);
  if (isNaN(num)) return value;
  
  return num.toFixed(2);
};

export default function ProjectTensionSectionsList({
  project,
  tensionSections,
  towers,
  crossingPoints,
  onEdit,
  onDelete,
  onAddNew,
}) {
  // 分页状态管理
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [filteredSections, setFilteredSections] = useState([]);

  // 过滤出当前项目的勘查单
  useEffect(() => {
    if (project && tensionSections) {
      const filtered = tensionSections.filter(
        (ts) => ts.projectId === project.id || project.projectId
      );
      setFilteredSections(filtered);
      // 重置到第一页
      setCurrentPage(1);
    }
  }, [project, tensionSections]);

  // 分页计算
  const totalItems = filteredSections.length;
  const totalPages = Math.ceil(totalItems / pageSize);
  const startIndex = (currentPage - 1) * pageSize;
  const currentPageData = filteredSections.slice(
    startIndex,
    startIndex + pageSize
  );

  // 分页操作
  const goToPage = (page) => {
    if (page >= 1 && page <= totalPages) {
      setCurrentPage(page);
    }
  };

  const getTowerNumber = (towerId) => {
    const tower = towers?.find((t) => t.id === towerId);
    return tower ? tower.towerNumber : "未知";
  };

  // 计算塔数（包含起始塔、结束塔和中间塔）
  const calculateTowerCount = (section) => {
    const intermediateCount = section.intermediateTowerIds 
      ? section.intermediateTowerIds.length 
      : 0;
    // 始终包含起始塔和结束塔
    return intermediateCount + 2;
  };

  // 生成页码按钮
  const renderPageNumbers = () => {
    const pageNumbers = [];
    const maxVisiblePages = 5;

    if (totalPages <= maxVisiblePages) {
      // 总页数少于等于5页，显示所有页码
      for (let i = 1; i <= totalPages; i++) {
        pageNumbers.push(i);
      }
    } else {
      // 总页数多于5页，显示当前页前后的页码
      const startPage = Math.max(1, currentPage - 2);
      const endPage = Math.min(totalPages, currentPage + 2);

      // 添加首页和可能的省略号
      if (startPage > 1) {
        pageNumbers.push(1);
        if (startPage > 2) {
          pageNumbers.push("...");
        }
      }

      // 添加中间页码
      for (let i = startPage; i <= endPage; i++) {
        pageNumbers.push(i);
      }

      // 添加尾页和可能的省略号
      if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
          pageNumbers.push("...");
        }
        pageNumbers.push(totalPages);
      }
    }

    return pageNumbers;
  };

  if (!project) return null;

  return (
    <Card className="mt-8 shadow-lg border-0">
      <CardHeader className="bg-gradient-to-r from-green-50 to-teal-50 border-b">
        <div className="flex items-center justify-between">
          <CardTitle className="text-xl font-bold text-gray-800 flex items-center gap-2">
            <GitBranch className="w-6 h-6 text-green-600" />
            勘查单列表
          </CardTitle>
          <Button onClick={onAddNew} variant="outline" size="sm">
            <Plus className="w-4 h-4 mr-2" />
            新增勘查单
          </Button>
        </div>
      </CardHeader>

      <CardContent className="p-6">
        {totalItems > 0 ? (
          <>
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>勘查单名称</TableHead>
                    <TableHead>起始塔</TableHead>
                    <TableHead>结束塔</TableHead>
                    <TableHead>塔数</TableHead>
                    <TableHead>总长度(m)</TableHead>
                    <TableHead>代表档距(m)</TableHead>
                    <TableHead>跨越点数</TableHead>
                    <TableHead className="text-right">操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {currentPageData.map((section) => (
                    <TableRow key={section.id} className="hover:bg-gray-50">
                      <TableCell className="font-medium">
                        <button
                          onClick={() => onEdit && onEdit(section)}
                          className="text-left hover:text-blue-600 hover:underline cursor-pointer focus:outline-none focus:underline"
                          title="点击编辑勘查单"
                        >
                          {section.name || "未命名勘查单"}
                        </button>
                      </TableCell>
                      <TableCell>
                        {getTowerNumber(section.startTensionTowerId)}
                      </TableCell>
                      <TableCell>
                        {getTowerNumber(section.endTensionTowerId)}
                      </TableCell>
                      <TableCell>
                        <Badge variant="outline" className="bg-blue-50">
                          {calculateTowerCount(section)}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        {section.totalLength ? (
                          <span className="font-medium text-green-600">
                            {formatNumber(section.totalLength)}
                          </span>
                        ) : (
                          <span className="text-gray-400">-</span>
                        )}
                      </TableCell>
                      <TableCell>
                        {section.calculatedRulingSpan ? (
                          <span className="font-medium text-purple-600">
                            {formatNumber(section.calculatedRulingSpan)}
                          </span>
                        ) : (
                          <span className="text-gray-400">-</span>
                        )}
                      </TableCell>
                      <TableCell>
                        <Badge 
                          variant="secondary" 
                          className={
                            section.associatedCrossingPointIds?.length > 0 
                              ? "bg-orange-100 text-orange-800 border-orange-200" 
                              : "bg-gray-100 text-gray-600"
                          }
                        >
                          {section.associatedCrossingPointIds
                            ? section.associatedCrossingPointIds.length
                            : 0}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-right">
                        <div className="flex justify-end gap-2">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => onEdit && onEdit(section)}
                            className="h-8 w-8 p-0 text-blue-600 hover:text-blue-800 hover:bg-blue-50"
                            title="编辑勘查单"
                          >
                            <Edit className="w-4 h-4" />
                          </Button>  
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => onDelete && onDelete(section.id)}
                            className="h-8 w-8 p-0 text-red-600 hover:text-red-700 hover:bg-red-50"
                            title="删除勘查单"
                          >
                            <Trash2 className="w-4 h-4" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>

            {/* 分页控件 */}
            <div className="flex flex-col sm:flex-row justify-between items-center mt-6 gap-4">
              <div className="text-sm text-gray-500">
                显示第 {startIndex + 1} 到 {Math.min(startIndex + pageSize, totalItems)} 条，
                共 {totalItems} 条数据
              </div>
              
              <div className="flex items-center gap-4">
                {/* 每页条数选择 */}
                <div className="flex items-center gap-2">
                  <span className="text-sm text-gray-600">每页</span>
                  <Select
                    value={pageSize.toString()}
                    onValueChange={(value) => {
                      setPageSize(Number(value));
                      setCurrentPage(1); // 重置到第一页
                    }}
                  >
                    <SelectTrigger className="w-20">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="5">5条</SelectItem>
                      <SelectItem value="10">10条</SelectItem>
                      <SelectItem value="20">20条</SelectItem>
                      <SelectItem value="50">50条</SelectItem>
                    </SelectContent>
                  </Select>
                  <span className="text-sm text-gray-600">条</span>
                </div>

                {/* 分页按钮 */}
                <div className="flex items-center gap-1">
                  {/* 首页按钮 */}
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => goToPage(1)}
                    disabled={currentPage === 1}
                    className="h-8 w-8 p-0"
                    title="首页"
                  >
                    <SkipBack className="w-3 h-3" />
                  </Button>
                  
                  {/* 上一页按钮 */}
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => goToPage(currentPage - 1)}
                    disabled={currentPage === 1}
                    className="h-8 w-8 p-0"
                    title="上一页"
                  >
                    <ChevronLeft className="w-3 h-3" />
                  </Button>

                  {/* 页码按钮 */}
                  {renderPageNumbers().map((page, index) => (
                    page === "..." ? (
                      <span 
                        key={`ellipsis-${index}`} 
                        className="flex items-center justify-center h-8 w-8 text-gray-400"
                      >
                        ...
                      </span>
                    ) : (
                      <Button
                        key={page}
                        variant={currentPage === page ? "default" : "outline"}
                        size="sm"
                        onClick={() => goToPage(page)}
                        className={`h-8 w-8 p-0 ${
                          currentPage === page 
                            ? "bg-green-600 text-white hover:bg-green-700" 
                            : ""
                        }`}
                      >
                        {page}
                      </Button>
                    )
                  ))}

                  {/* 下一页按钮 */}
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => goToPage(currentPage + 1)}
                    disabled={currentPage === totalPages}
                    className="h-8 w-8 p-0"
                    title="下一页"
                  >
                    <ChevronRight className="w-3 h-3" />
                  </Button>
                  
                  {/* 末页按钮 */}
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => goToPage(totalPages)}
                    disabled={currentPage === totalPages}
                    className="h-8 w-8 p-0"
                    title="末页"
                  >
                    <SkipForward className="w-3 h-3" />
                  </Button>
                </div>
              </div>
            </div>
          </>
        ) : (
          <div className="text-center py-12 border-2 border-dashed border-gray-200 rounded-lg">
            <GitBranch className="w-16 h-16 text-gray-300 mx-auto mb-4" />
            <p className="text-gray-500 mb-2">该项目下暂无勘查单</p>
            <p className="text-sm text-gray-400 mb-4">
              请添加勘查单以进行施工规划
            </p>
            <Button onClick={onAddNew}>
              <Plus className="w-4 h-4 mr-2" />
              新增第一个勘查单
            </Button>
          </div>
        )}
      </CardContent>
    </Card>
  );
}

// 导出数值格式化函数，供其他组件使用
export { formatNumber, formatNumberFixed };